// pages/food/food.js

const config = require('../../config/config.js')
const util = require('../../utils/util.js')
const commentCard = require('../../commentCard/commentCard.js')

const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    foodId: 0,
    grids: [],
    foodName: '',
    collectNum: 0,
    foodDesc: '',
    foodFlavor: '',
    foodImgUrl: '',
    foodStyle: '',
    price: 0,
    score: 0,
    shopId: 0,
    shopName: '',
    shopHeadImgUrl: '',
    starShine: "./../../imgs/star_shine.png",
    star: "./../../imgs/star.png",
    isSelf: false,
    latitude: 0,
    longitude: 0,
    comments: [],
    isMoreComments: false,
    isHaveComment: false,
    isCollect: false,
    showSharePanel: false

  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let food_id = options.food_id
    if (!food_id && options.scene) {
      let scene = decodeURIComponent(options.scene)
      food_id = parseInt(scene)
    }
    let that = this
    // console.log(food_id)
    // console.log(wx.getStorageSync('openid'))
    wx.request({
      url: `${config.requestBaseUrl}/Dishes/getFoodInfo`,
      method: 'POST',
      data: {
        food_id: food_id,
        openid: wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.data.code === 1) {
          let imgGrids = []
          if (res.data.desc_img1 != "")
            imgGrids.push(res.data.desc_img1)
          if (res.data.desc_img2 != "")
            imgGrids.push(res.data.desc_img2)
          if (res.data.desc_img3 != "")
            imgGrids.push(res.data.desc_img3)
          that.setData({
            foodId: food_id,
            grids: imgGrids,
            shopId: res.data.shop_id,
            foodName: res.data.food_name,
            collectNum: res.data.collect_num,
            foodDesc: res.data.desc_text,
            foodFlavor: res.data.food_flavor,
            foodImgUrl: res.data.food_img,
            foodStyle: res.data.food_style,
            price: res.data.price,
            score: res.data.star_score,
            isSelf: wx.getStorageSync('openid') == res.data.openid
          })
          that.getShopInfo()
          that.getComments()
        } else {
          console.log("没有找到菜品信息")
        }
      }
    })

    

  },

  getShopInfo: function() {
    let that = this
    wx.request({
      url: `${config.requestBaseUrl}/Shop/getShopInfo`,
      method: 'POST',
      data: {
        shop_id: that.data.shopId,
        openid: wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.data.code === 1) {
          that.setData({
            shopHeadImgUrl: res.data.logo_url,
            shopName: res.data.shop_name,
            longitude: res.data.longitude,
            latitude: res.data.latitude
          })
        } else {
          console.log("没有找到商户信息")
        }
      }
    })

  },

  getComments: function () {
    let that = this
    // console.log(this.data.foodId)
    wx.request({
      url: `${config.requestBaseUrl}/Comment/getCommentsByFoodId`,
      method: 'POST',
      data: {
        food_id: that.data.foodId,
        limit: 3
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        that.setData({
          isHaveComment: res.data.code != 0,
        })
        if (that.data.isHaveComment) {
          let data = res.data.data
          // console.log(data)
          for (let i = 0, len = data.length; i < len; i++) {
            data[i]['create_time'] = data[i]['create_time'].trim().split(" ")[0]
            let imgGrids = []
            if (data[i]['comment_img1'] != null && data[i]['comment_img1'].length > 0) {
              imgGrids.push(data[i]['comment_img1'])
            }
            if (data[i]['comment_img1'] != null && data[i]['comment_img2'].length > 0) {
              imgGrids.push(data[i]['comment_img2'])
            }
            if (data[i]['comment_img1'] != null && data[i]['comment_img3'].length > 0) {
              imgGrids.push(data[i]['comment_img3'])
            }
            data[i]['imgs'] = imgGrids
          }
          that.setData({
            comments: data,
            isMoreComments: res.data.count > 3
          })
        }
      }
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {
    return {
      title: this.data.foodName,
      desc: this.data.foodDesc.length > 20 ? this.data.foodDesc.substring(20) + '...' : this.data.foodDesc,
      path: `page/food/food?food_id=${foodId}`
    }
  },

  // 编辑菜品信息
  editFoodInfo: function () {
    wx.navigateTo({
      url: `../foodform/foodform?food_id=${this.data.foodId}&shop_id=${this.data.shopId}&latitude=${this.data.latitude}&longitude=${this.data.longitude}`,
    })
  },

  previewDescImg: function(e) {
    let index = e.currentTarget.dataset.index
    let imgGrids = this.data.grids
    wx.previewImage({
      current: imgGrids[index],
      urls: imgGrids,
    })
  },

  clickComment: function() {
    let that = this
    if (app.globalData.userInfo) {
      wx.navigateTo({
        url: `../comment/comment?food_id=${this.data.foodId}&comment_id=0`,
      })
    } else if (wx.canIUse('button.open-type.getUserInfo')) {
      app.getUserInfoSuccessCallBack = function() {
        wx.redirectTo({
          url: `/pages/comment/comment?food_id=${that.data.foodId}&comment_id=0`,
        })
      }
      app.getUserInfoFailCallBack = function() {
        wx.redirectTo({
          url: `/pages/food/food?food_id=${that.data.foodId}`,
        })
      }
      wx.redirectTo({
        url: `../userinfo/userinfo`,
      })
    } else {
      // 在没有 open-type=getUserInfo 版本的兼容处理
      wx.getUserInfo({
        success: res => {
          app.globalData.userInfo = res.userInfo
          // this.setData({
          //   userInfo: res.userInfo,
          //   hasUserInfo: true
          // })
        }
      })
    }
    
  },

  clickCommentsShow: function() {
    wx.navigateTo({
      url: `../commentsshow/commentsshow?food_id=${this.data.foodId}`,
    })
  },


  clickCollectFood: function() {
    let that = this
    wx.request({
      url: `${config.requestBaseUrl}/Collect/CollectFood`,
      method: 'POST',
      data: {
        food_id: this.data.foodId,
        openid: wx.getStorageSync('openid')
      },
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      success: function (res) {
        // console.log(res)
        if (res.data.code != 0) {
          that.setData({
            isCollect: res.data.code === 1 ? true : false
          })
        }
      }
    })
  },


  clickShareBtn: function() {
    this.setData({
      showSharePanel: !this.data.showSharePanel
    })
  },

  generateFoodShareImg: function() {
    let data = {
      foodId: this.data.foodId,
      foodName: this.data.foodName,
      foodDesc: this.data.foodDesc,
      foodFlavor: this.data.foodFlavor,
      foodImgUrl: this.data.foodImgUrl,
      foodStyle: this.data.foodStyle,
      price: this.data.price,
      score: this.data.score,
      shopName: this.data.shopName,
      shopHeadImgUrl: this.data.shopHeadImgUrl,
    }
    let dataJson = JSON.stringify(data)
    wx.redirectTo({
      url: `../foodcanvas/foodcanvas?data=${dataJson}`,
    })
  },

  previewCommentImg: function(e) {
    // console.log(e)
    let index = e.currentTarget.dataset.index
    let urls = e.currentTarget.dataset.imgs
    // console.log(urls)
    commentCard.previewCommentImg(index, urls)
  }





})